import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-10-23
 * Time: 21:29
 */
public class TcpEchoServer {
    public ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket socket = serverSocket.accept();
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(()->{
                try {
                    processConection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    private void processConection(Socket socket) throws IOException {
        System.out.printf("客户端[%s:%d]上线!\n", socket.getInetAddress(), socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                Scanner scanner = new Scanner(inputStream);
                PrintWriter writer = new PrintWriter(outputStream)){
                while(true) {

                    if(!scanner.hasNext()){
                        System.out.printf("客户端[%s:%d]下线!\n", socket.getInetAddress(), socket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    String response = process(request);

                    writer.println(response);
                    //刷新缓冲区
                    writer.flush();
                    System.out.printf("[%s:%d] req:%s, res:%s\n", socket.getInetAddress(), socket.getPort(), request, response);
                }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            socket.close();
        }
    }
    private String process(String requset){
        return requset;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
